package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.annotation.RequiresPermissionsDesc;
import com.qf.pojo.DtsStorage;
import com.qf.service.StorageService;
import com.qf.util.ResponseUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/admin/storage")
public class StorageController {

    @Autowired
    private StorageService storageService;

    @PostMapping("/create")
    public Object create(MultipartFile file)throws Exception{
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String filename = file.getOriginalFilename();
        DtsStorage dtsStorage = storageService.insert( filename,ext,
                file.getSize(),file.getBytes());
        return ResponseUtil.ok(dtsStorage);
    }

    //http://localhost:8080/admin/storage/list?
    // page=1&limit=20&key=asdf&name=asdf&sort=add_time&order=desc
    @RequiresPermissions("admin:storage:list")
    @RequiresPermissionsDesc(menu = {"系统管理","对象存储"},button = "查询")
    @GetMapping("/list")
    public Object list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "20") Integer limit,
                       String key,String name,String sort,String order){
        IPage iPage=storageService.findListByQuery(page,limit,key,name,sort,order);
        Map data=new HashMap();
        data.put("total",iPage.getTotal());
        data.put("items",iPage.getRecords());
        return ResponseUtil.ok(data);
    }

    @RequiresPermissions("admin:storage:update")
    @RequiresPermissionsDesc(menu = {"系统管理","对象存储"},button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody DtsStorage dtsStorage){
        dtsStorage.setUpdateTime(new Date());
        storageService.updateStorageName(dtsStorage);
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:storage:delete")
    @RequiresPermissionsDesc(menu = {"系统管理","对象存储"},button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsStorage dtsStorage){
        dtsStorage.setDeleted(true);
        storageService.updateStorageName(dtsStorage);
        return ResponseUtil.ok();
    }

}
